package corestruct

import (
	"database/sql/driver"
	"errors"
	"time"
)

const (
	DateTimeFmt = "2006-01-02 15:04:05"
	DateFmt     = "2006-01-02"
)

type MyTime time.Time

func (t *MyTime) UnmarshalJSON(data []byte) (err error) {
	var fmt = DateTimeFmt
	if len(data) == 12 {
		fmt = DateFmt
	}
	now, err := time.ParseInLocation(`"`+fmt+`"`, string(data), time.Local)
	*t = MyTime(now)
	return
}

func (t MyTime) MarshalJSON() ([]byte, error) {
	b := make([]byte, 0, len(DateTimeFmt)+2)
	b = append(b, '"')
	b = time.Time(t).AppendFormat(b, DateTimeFmt)
	b = append(b, '"')
	return b, nil
}

func (t MyTime) String() string {
	return time.Time(t).Format(DateTimeFmt)
}

func (t *MyTime) Scan(value any) error {

	if v, ok := value.(time.Time); !ok {
		return errors.New("failed to unmarshal CustomTime value: %v")
	} else {
		*t = MyTime(v)
		return nil
	}
}

// GORM Valuer 接口, 保存到数据库
func (t MyTime) Value() (driver.Value, error) {
	if time.Time(t).IsZero() {
		return nil, nil
	}
	return time.Time(t), nil
}

func Now() MyTime {
	return MyTime(time.Now())
}
